package com.example.dts.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dts.mapper.StudioMapper;
import com.example.dts.model.Studio;
import com.example.dts.model.ro.StudioRO;
import com.example.dts.model.vo.StudioVO;
import com.example.dts.service.FileService;
import com.example.dts.service.StudioService;
import com.example.dts.type.FileType;
import com.example.dts.utils.LiveUrlUtil;
import com.example.dts.utils.SpringUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@Service
public class StudioServiceImpl extends ServiceImpl<StudioMapper,Studio> implements StudioService {

    @Resource
    private StudioMapper studioMapper;

    @Value("${coverPath}")
    String coverPath;


    @Value("${host}")
    String host;

    @Value("${server.port}")
    private String port;

    @Value("${domainName}")
    String domainName;

    @Resource
    private FileService fileService;

    String appName = RandomStringUtils.randomAlphanumeric(5);

    String streamName = RandomStringUtils.randomAlphanumeric(5);

    long expireTime = 360000L;

    String pullDomain = "pull.pengqing.icu";

    String pullKey = "4bom479uDySjpv4b";

    String pushDomain = "push.pengqing.icu";

    String pushKey = "z2rDfw4kyqYMQUBr";

    @Resource
    private SpringUtil springUtil;


    @Override
    public void add(StudioRO ro) {
        Studio studio = new Studio();
        try {
            BeanUtils.copyProperties(studio,ro);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        studioMapper.insert(studio);
    }

    @Override
    public StudioVO createStudio(StudioRO studioRO, String userId) {
        Studio studio = new Studio();
        try {
            BeanUtils.copyProperties(studio, studioRO);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }

        //推流地址
        String pushUrl = LiveUrlUtil.generate_push_url(pushDomain, pushKey, appName, streamName, expireTime);
        //拉流地址
        Map<String, String> pullUrlMap = LiveUrlUtil.general_pull_url(pullDomain, pullKey, appName, streamName, expireTime);
        studio.setPullUrl(pullUrlMap.get("rtmpUrl"));
        studio.setPushUrl(pushUrl);
        studio.setCreateUserId(userId);
        this.save(studio);
        StudioVO vo = new StudioVO();
        try {
            BeanUtils.copyProperties(vo, studio);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return vo;
    }

    /**
     * 获取热门直播，取观看人数或预约人数最多的三个
     * @return
     */
    @Override
    public List<Studio> getHotLives() {
        QueryWrapper<Studio> qw = new QueryWrapper<>();
        qw.eq("deleted",0);
        qw.last("limit 0,3");
        qw.orderByDesc(true,"appointment_number + watch_number");
        List<Studio> hotLives = studioMapper.selectList(qw);
        return hotLives;
    }


    @Override
    public String uploadImg(MultipartFile file, String userId) {
        System.out.println("上传直播间封面图片");
        String fileName = file.getOriginalFilename();
        File dest = new File(coverPath+fileName);
        byte environ = springUtil.getEnviron();
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),dest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String url="";
        if(environ==0){
            url = domainName + ":" + port + coverPath.substring(16) + fileName;
        } else {
            url = domainName + ":" + port + coverPath.substring(18) + fileName;
        }
        com.example.dts.model.File file1 = new com.example.dts.model.File();
        file1.setType(FileType.COVER);
        file1.setPath(coverPath);
        file1.setUrl(url);
        file1.setCreateUserId(userId);
        fileService.saveFile(file1, userId);
        System.out.println("图片上传成功，图片url：" +  url);
        return url;
    }
}
